package com.itcm.skymail.auth.controller;

import com.itcm.common.constant.AuthServerConstant;
import com.itcm.common.utils.R;
import com.itcm.common.vo.ResultMemberVo;
import com.itcm.skymail.auth.feign.MemberFeignService;
import com.itcm.skymail.auth.vo.LoginUserVo;
import com.itcm.skymail.auth.vo.UserRegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 描述:
 *
 * @author cm_fighting
 * @create 2020-11-05 5:41 下午
 */
@Controller
public class IndexController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberFeignService memberFeignService;

    //todo : 分布式下的session问题
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes attributes) {
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            /*
                重定向携带数据 利用session原理 将数据放在session中
                只要跳转页面取出这个数据，session里面的数据就会删掉
             */
            attributes.addFlashAttribute("errors", errors);
            /**
             * 这是发生错误 应该还是到当前注册页 并回显错误信息
             * 但是 不能用 forward 转发 因为我们配置的注册页面(路经映射)接受的是get请求，当前是post
             */
            return "redirect:http://auth.skymail.com/register.html";
        }
        // 校验通过 需要调用远程服务注册
        // 先校验验证码
        String code = vo.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(s)) {
            if (s.split("_")[0].equals(code)) {
                // 删除redis中的验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                // 远程调用 skymail-member
                R r = memberFeignService.regist(vo);
                if (r.getCode() == 0) {
                    return "redirect:http://auth.skymail.com/login.html";
                } else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("message", (String) r.get("msg"));
                    attributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.skymail.com/register.html";
                }
            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                attributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.skymail.com/register.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.skymail.com/register.html";
        }
    }

    @PostMapping("/login")
    public String login(LoginUserVo vo, HttpSession session) {
        // 远程 ：skymail-member
        System.out.println("------ login ------");
        ResultMemberVo member = memberFeignService.login(vo);
        if (member != null) {
            session.setAttribute(AuthServerConstant.LOGIN_USER, member);
            return "redirect:http://skymail.com";
        } else {
            return "redirect:http://auth.skymail.com/login.html";
        }
    }
}
